package club.pinea.handler.lobby;

import club.pinea.annotations.Head;
import club.pinea.interfaces.TCPMessage;
import club.pinea.model.Seat;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.LobbyProto;
import club.pinea.send.MessageSend;
import club.pinea.service.SeatService;
import club.pinea.service.UserService;
import club.pinea.session.GlobalServerPlayerContainer;
import club.pinea.session.IOSession;
import club.pinea.session.ServerPlayer;
import club.pinea.utils.AsyncManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.TimerTask;


/**
 * @description: 座位留机处理
 * @author: 华上进
 * @createTime: 2021/6/30 9:40
 */
@Head(CommandProto.Command.C_S_STAY_SEAT_VALUE)
@Component
public class StaySeatHandler implements TCPMessage<BasicProto.BaseMessage> {

    /**
     * redis座位操作服务类
     */
    @Autowired
    private SeatService seatService;

    /**
     * 用户操作服务类
     */
    @Autowired
    private UserService userService;


    /**
     * 当前用户是否坐在某个座位上
     */
    private Seat seat;

    private String userName;

    /**
     * @description: 座位留机处理 相关操作
     * @author: 华上进
     * @createTime: 2021/6/30 11:06
     */
    @Override
    public void doMessage(BasicProto.BaseMessage msg, IOSession session) throws Exception {
        // 座位留机处理 请求参数
        LobbyProto.StaySeatRequest request = LobbyProto.StaySeatRequest.parseFrom(msg.getBody());
        ServerPlayer serverPlayer = GlobalServerPlayerContainer.getServerPlayer(session);
        // 座位id
        int seatId = request.getSeatNum();
        userName = userService.getUserName(request.getUserId());
        // 根据用户Id查找用户剩余留机次数
        int staySeatTime = userService.selectStaySeatTimeById(request.getUserId());
        if (staySeatTime < 0) {
            throw new IllegalArgumentException("今日留机次数已用完，留机失败！");
        }
        seat = seatService.getSeatBean(seatId, serverPlayer.getRoom());
        seatService.updateSeatsInfoForStaySeat(userName, seatId, serverPlayer.getRoom());
        Seat s = new Seat(seat.getSeatId());
        AsyncManager.me().executeDelay(new TimerTask() {
            @Override
            public void run() {
                int result = seatService.formatSeatByStaySeats(s, seatId, serverPlayer.getRoom());//更新座位信息
                if (result > 0) {
                }
            }
        });
        seat = null;

        LobbyProto.StaySeatResponse response = LobbyProto.StaySeatResponse.newBuilder()
                .setRes(MessageSend.successRes())
                .build();
        // 返回消息
        MessageSend.sendToUser(response, session);
    }


}
